"use client"

import React, { useState } from "react"
import { Drawer, Box, Typography, IconButton, Paper, Tabs, Tab, Tooltip, Snackbar, Alert, Divider } from "@mui/material"
import { Close as CloseIcon, ContentCopy as CopyIcon, Visibility as PreviewIcon, Code as CodeIcon } from "@mui/icons-material"
import useAppStore from "@/store/useAppStore"

export default function HtmlPreviewSidebar() {
	const { sidebarOpen, sidebarContent, sidebarTitle, setSidebarOpen } = useAppStore()
	const [activeTab, setActiveTab] = useState(0)
	const [copySuccess, setCopySuccess] = useState(false)

	// 提取 HTML 内容（去除可能的 markdown 代码块标记）
	const cleanHtmlContent =
		sidebarContent
			?.replace(/```html\n?/g, "")
			.replace(/```\n?/g, "")
			.trim() || ""

	const handleTabChange = (_: React.SyntheticEvent, newValue: number) => {
		setActiveTab(newValue)
	}

	const handleCopyCode = async () => {
		try {
			await navigator.clipboard.writeText(cleanHtmlContent)
			setCopySuccess(true)
		} catch (err) {
			console.error("复制失败:", err)
		}
	}

	const handleCloseCopySuccess = () => {
		setCopySuccess(false)
	}

	const handleClose = () => {
		setSidebarOpen(false)
	}

	return (
		<>
			<Drawer
				anchor='right'
				open={sidebarOpen}
				onClose={handleClose}
				sx={{
					"& .MuiDrawer-paper": {
						width: { xs: "100%", sm: 500, md: 600 },
						background: "rgba(255, 255, 255, 0.95)",
						backdropFilter: "blur(20px)",
						borderLeft: "1px solid rgba(148, 163, 184, 0.2)"
					}
				}}
			>
				<Box sx={{ height: "100%", display: "flex", flexDirection: "column" }}>
					{/* 侧栏头部 */}
					<Box
						sx={{
							display: "flex",
							alignItems: "center",
							justifyContent: "space-between",
							px: 2,
							py: 1.5,
							borderBottom: "1px solid rgba(148, 163, 184, 0.2)"
						}}
					>
						<Typography variant='h6' sx={{ fontWeight: 600, color: "text.primary" }}>
							{sidebarTitle}
						</Typography>
						<IconButton onClick={handleClose} size='small'>
							<CloseIcon />
						</IconButton>
					</Box>

					{/* 标签页导航 */}
					<Box sx={{ borderBottom: "1px solid rgba(148, 163, 184, 0.2)" }}>
						<Tabs
							value={activeTab}
							onChange={handleTabChange}
							sx={{
								px: 2,
								"& .MuiTab-root": {
									textTransform: "none",
									fontSize: "0.875rem",
									fontWeight: 500,
									minHeight: 48
								}
							}}
						>
							<Tab icon={<PreviewIcon fontSize='small' />} label='预览' iconPosition='start' />
							<Tab icon={<CodeIcon fontSize='small' />} label='代码' iconPosition='start' />
						</Tabs>
					</Box>

					{/* 内容区域 */}
					<Box sx={{ flexGrow: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>
						{activeTab === 0 && (
							// 预览模式
							<Box
								sx={{
									flexGrow: 1,
									p: 2,
									overflow: "auto",
									"& *": {
										maxWidth: "100%"
									}
								}}
							>
								<Paper
									elevation={0}
									sx={{
										p: 2,
										bgcolor: "background.paper",
										border: "1px solid rgba(148, 163, 184, 0.2)",
										borderRadius: 2,
										minHeight: "100%"
									}}
								>
									{cleanHtmlContent ? (
										<Box
											dangerouslySetInnerHTML={{ __html: cleanHtmlContent }}
											sx={{
												"& *": {
													maxWidth: "100%"
												}
											}}
										/>
									) : (
										<Box
											sx={{
												display: "flex",
												alignItems: "center",
												justifyContent: "center",
												height: "200px",
												color: "text.secondary"
											}}
										>
											<Typography variant='body2'>暂无HTML内容</Typography>
										</Box>
									)}
								</Paper>
							</Box>
						)}

						{activeTab === 1 && (
							// 代码模式
							<Box sx={{ flexGrow: 1, display: "flex", flexDirection: "column" }}>
								{/* 代码操作栏 */}
								<Box
									sx={{
										display: "flex",
										alignItems: "center",
										justifyContent: "space-between",
										px: 2,
										py: 1,
										borderBottom: "1px solid rgba(148, 163, 184, 0.2)"
									}}
								>
									<Typography variant='caption' color='text.secondary'>
										HTML 代码
									</Typography>
									<Tooltip title='复制代码'>
										<IconButton size='small' onClick={handleCopyCode}>
											<CopyIcon fontSize='small' />
										</IconButton>
									</Tooltip>
								</Box>

								{/* 代码显示区域 */}
								<Box
									sx={{
										flexGrow: 1,
										overflow: "auto",
										"& pre": {
											margin: 0,
											padding: 2,
											background: "rgba(15, 23, 42, 0.05)",
											borderRadius: 0,
											fontSize: "0.875rem",
											fontFamily: 'Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
											lineHeight: 1.5,
											whiteSpace: "pre-wrap",
											wordBreak: "break-all"
										}
									}}
								>
									<pre>{cleanHtmlContent || "暂无HTML代码"}</pre>
								</Box>
							</Box>
						)}
					</Box>
				</Box>
			</Drawer>

			{/* 复制成功提示 */}
			<Snackbar open={copySuccess} autoHideDuration={2000} onClose={handleCloseCopySuccess} anchorOrigin={{ vertical: "top", horizontal: "center" }}>
				<Alert onClose={handleCloseCopySuccess} severity='success' variant='filled' sx={{ fontSize: "0.875rem" }}>
					HTML 代码已复制到剪贴板！
				</Alert>
			</Snackbar>
		</>
	)
}
